package cn.wildfire.chat.kit.user;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.BoxingCrop;
import com.bilibili.boxing.BoxingMediaLoader;
import com.bilibili.boxing.loader.IBoxingMediaLoader;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.config.BoxingCropOption;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.utils.BoxingFileHelper;
import com.bilibili.boxing_impl.ui.BoxingActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lqr.imagepicker.ImagePicker;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.Locale;

import androidx.lifecycle.MutableLiveData;
import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.classes.BoxingGlideLoader;
import cn.wildfire.chat.app.extendsion.classes.BoxingUcrop;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.common.OperateResult;

public class ChangeHeadActivity extends WfcBaseActivity {

    private static final int CLIP_REQUEST_CODE = 100;

    @BindView(R2.id.iv_preview)
    ImageView ivPreview;

    UserViewModel userViewModel;
    String imagePath;
    String portrait;

    @Override
    protected void afterViews() {
        super.afterViews();

        userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        Intent intent = getIntent();
        portrait = intent.getStringExtra("portrait");

        Glide.with(this).load(this.portrait).apply(new RequestOptions().
                placeholder(R.mipmap.avatar_def).centerCrop()).into(ivPreview);
    }


    @Override
    protected int contentLayout() {
        return R.layout.activity_change_head;
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 3);
        setReplaceTitle(null, R.string.modify_head);
        setSearchLayoutVisibility(false);
        getRightTxtView().setBackgroundResource(R.drawable.commom_green_radiusmuch);
        getRightTxtView().setTextColor(getResources().getColor(R.color.white));
        setTextThenBinClickForRightTextView(View.VISIBLE, getString(R.string.text_modify), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveHead();
            }
        });
        try {
            //选择glide加载框架 BoxingGlideLoader是自定义实现
            IBoxingMediaLoader loader = new BoxingGlideLoader();
            BoxingMediaLoader.getInstance().init(loader);
            //初始化裁剪功能 BoxingUcrop是自定义实现
            BoxingCrop.getInstance().init(new BoxingUcrop());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R2.id.iv_preview})
    public void onClick(View view) {
        if (view.getId() == R.id.iv_preview) {
            getImage();
        }
    }

    private static final int REQUEST_CODE_PICK_IMAGE = 100;

    private void updatePortrait() {
        ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
    }

    private void getImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MANAGE_DOCUMENTS}, 1001);
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ToastTip.tip(getString(R.string.need_check_local_files_permission));
                return;
            }
        }
        //获取缓存的存储路径
        String cachePath = BoxingFileHelper.getCacheDir(ChangeHeadActivity.this);
        if (TextUtils.isEmpty(cachePath)) {
            Toast.makeText(getApplicationContext(),"设备存储读取出错或暂不可用，请稍候重试", Toast.LENGTH_SHORT).show();
            return;
        }
        Uri destUri = new Uri.Builder()
                .scheme("file")
                .appendPath(cachePath)
                .appendPath(String.format(Locale.US, "%s.png", System.currentTimeMillis()))
                .build();
        BoxingConfig singleCropImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).withCropOption(new BoxingCropOption(destUri))
                .withMediaPlaceHolderRes(R.mipmap.default_header);
        Boxing.of(singleCropImgConfig).withIntent(ChangeHeadActivity.this, BoxingActivity.class)
                .start(ChangeHeadActivity.this, CLIP_REQUEST_CODE);
    }

    private void saveHead(){
        if (imagePath == null || imagePath.equals("")) {
            getImage();
        } else if (imagePath != null && !imagePath.equals("")) {
            MutableLiveData<OperateResult<Boolean>> result = userViewModel.updateUserPortrait(imagePath);
            result.observe(this, booleanOperateResult -> {
                if (booleanOperateResult.isSuccess()) {
                    Toast.makeText(this, getString(R.string.update_head_success), Toast.LENGTH_SHORT).show();
                    onBackPressed();
                    onBackPressed();
                    finish();
                } else {
                    Toast.makeText(this, getString(R.string.update_head_failure) + booleanOperateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
        if (requestCode == CLIP_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            final ArrayList<BaseMedia> medias = Boxing.getResult(data);
            if (data != null) {
                BaseMedia media = medias.get(0);
                String path;
                if (media instanceof ImageMedia) {
                    path = ((ImageMedia) media).getThumbnailPath();
                } else {
                    path = media.getPath();
                }
                imagePath = path;
                int targetSize = getResources().getDisplayMetrics().widthPixels;
                BoxingMediaLoader.getInstance().displayThumbnail(ivPreview, path, targetSize, targetSize);
            } else {
                Toast.makeText(this, "图片损坏，请重新选择", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
